package org.penguin.boot.security.provider;

import lombok.RequiredArgsConstructor;
import org.penguin.boot.security.entity.PenguinUserDetails;
import org.penguin.boot.security.service.impl.PenguinUserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author : cyhch
 * @version : 1.0
 * @createdTime : 2023/12/24 11:02
 * @since : 1.0
 */


@Component // 添加盐值才使用
@RequiredArgsConstructor
public class PenguinAuthenticationProvider implements AuthenticationProvider {
    private final PasswordEncoder passwordEncoder;

    private final PenguinUserDetailsServiceImpl userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();
        String rawPassword = (String) authentication.getCredentials();
        PenguinUserDetails userDetails = userService.loadUserByUsername(userName);
        if (authentication.getCredentials() == null) {
            throw new BadCredentialsException("用户名或密码错误！");
        } else if (!passwordEncoder.matches(rawPassword + userDetails.getSalt(), userDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误！");
        } else {
            UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
            return result;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
